import React, { PureComponent } from 'react';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import { Modal, Button, message, Input, Select } from 'antd';
import { Form } from '@ant-design/compatible';
import { transferOption } from "@/utils/common";
import { findDicByCodeSort } from "@/support/common";
import PropTypes from "prop-types";

const FormItem = Form.Item;
const {TextArea} = Input;
@connect()
@Form.create({
    mapPropsToFields(props) {
        const formDataEdit = Object.assign({}, props.formData);
        for (const i in formDataEdit) {
            if(i === "mailPlatform" && formDataEdit[i]){
                formDataEdit[i]=Form.createFormField({value:formDataEdit[i] + ""});
            } else {
                formDataEdit[i]= Form.createFormField({value:formDataEdit[i]});
            }
        }
        return formDataEdit;
    },
})
export default class ThirdModal extends PureComponent<any, any> {

    static contextTypes = {
        permissions: PropTypes.array,
        dicData: PropTypes.object,
    };

    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            platformData: []
        };
    }

    componentDidMount() {
        this.initPlatformData()
    }

    initPlatformData = () => {
        this.props.dispatch({
            type: 'http/getData',
            payload: {
              url: '/message/channel/platform/list',
            },
            callback: (res: any) => {
                if (res.statusCode === '0') {
                    // data
                    this.setState({
                        platformData: res.data
                    })
                }
            }
        })
    }

    handleSubmit = () => {
        const { form: { validateFieldsAndScroll }, dispatch, formData, handleFlush} = this.props;
        validateFieldsAndScroll((err: any, values: any) => {
            if (err) return;
            const data = {...values};
            // 判断属于什么操作   1新增2编辑
            if(formData.thirdCd){
                data.flag = 2
            } else {
                data.flag =1
            }
            this.setState({ loading: true});
            dispatch({
                type: 'messageChannel/postObjWithRes',
                payload: { url: "/message/channel/updateThird", ...data },
                callback: (response: any) => {
                    if(response.statusCode === '0') {
                        message.success( formData.thirdCd ? '编辑成功': '新增成功');
                        this.handleClose();
                        handleFlush();
                    }
                    this.setState({ loading: false});
                },
            });
        });
    };

    handleClose = () => {
        const { changeVisible } = this.props;
        const { resetFields } = this.props.form;
        resetFields();
        changeVisible();
    };

    render() {
        const { formData, visible } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { loading, platformData } = this.state;
        // const messageCenterThirdList = findDicByCodeSort(this.context.dicData,"messageCenterThird");
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 12 },
                md: { span: 16 },
            },
        };
        return (
            <Modal
                style={{ top: 20 }}
                title={formData.thirdCd ? "编辑" : '新增'}
                wrapClassName="wrapModel"
                visible={visible}
                onCancel={() => this.handleClose()}
                footer={[
                    <Button size="small" key="back" type="ghost" onClick={() => this.handleClose()}>
                        取消
                    </Button>,
                    <Button size="small" key="submit" type="primary" loading={loading} onClick={() => this.handleSubmit()}>
                        保存
                    </Button>,
                ]}
            >
                <Form style={{ marginTop: 12 }}>
                    <FormItem
                        {...formItemLayout}
                        label="第三方渠道编码"
                    >
                        {getFieldDecorator('thirdCd', {
                            rules: [{ required: true, message: '第三方渠道编码不能为空！'}, {  message: '第三方渠道编码不能超过50位!',max:50 }],
                        })(
                            <Input disabled={!!formData.thirdCd} placeholder="请输入第三方渠道编码" maxLength={50} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="第三方渠道平台"
                    >
                        {getFieldDecorator('platform', {
                            rules: [{ required: true, message: '第三方渠道平台不能为空！' }],
                        })(
                            <Select
                                allowClear
                                placeholder="请选择第三方渠道平台"
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                {/* { transferOption(messageCenterThirdList,["dictKey","dictValue"])} */}
                                { transferOption(platformData,["platformCode","platformName"])}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="AppKey"
                    >
                        {getFieldDecorator('appKey', {
                            // rules: [{ required: true, message: 'AppKey不能为空！', },{message: 'AppKey不能超过150位!',max:150 }],
                        })(
                            <Input placeholder="请输入AppKey" maxLength={150} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="AppSecret"
                    >
                        {getFieldDecorator('appSecret', {
                            // rules: [{ required: true, message: 'AppSecret不能为空！' },{message: 'AppSecret不能超过150位!',max:150 }],
                        })(
                            <Input.Password placeholder="请输入AppSecret" maxLength={150} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="Token URL"
                    >
                        {getFieldDecorator('tokenUrl', {
                            // rules: [{ required: true, message: 'Token URL不能为空！' },{message: 'Token URL不能超过150位!',max:150 }],
                        })(
                            <Input placeholder="请输入Token URL" maxLength={150} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="推送URL"
                    >
                        {getFieldDecorator('pushUrl', {
                            // rules: [{ required: true, message: '推送URL不能为空！' },{message: '推送URL不能超过150位!',max:150 }],
                        })(
                            <Input placeholder="请输入推送URL" maxLength={150} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="扩展字段"
                    >
                        {getFieldDecorator('otherParams', {
                            // rules: [{message: '扩展字段不能超过500位!',max:500 }],
                        })(
                            <TextArea rows={4} placeholder='扩展字段格式为JSON，例如：{"event_id":"2"}' maxLength={500} />
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}
